﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NetDimension.OpenPlatform;
using TC.WEB.Site.Models;
using TC.WEB.Site.Core;
using TC.WEB.Site.Models.Tools;

namespace TC.SSO.Server.Controllers
{
    /// <summary>
    /// 第三方登录 接口
    /// </summary>
    public class ThirdController : Controller
    {
        const string SEESION_CLIENT = "__session_client";
        const string QQAPPID = "101231038";
        const string WEIBOAPPID = "754353753";
        /// <summary>
        /// 第三方登录 QQ
        /// </summary>
        /// <returns></returns>
        public ActionResult QQ()
        {
            var qq = new TencentClient(QQAPPID, "1ee266aeb963732459272619bb2b0c83",
                    "http://pass.buildnet.cn/third/qq");//qq的回调地址
            if (!string.IsNullOrWhiteSpace(Request["create"]))
            {
                string redirect = Request["redirect"];
                if(!string.IsNullOrWhiteSpace(redirect))
                    redirect = "&" + redirect;
                return Redirect(qq.GetAuthorizeUrl() + redirect);
            }
            if (!string.IsNullOrWhiteSpace(Request["code"]))
            {
                qq.GetAccessTokenByAuthorizationCode(Request["code"]);
                string opendIdUrl = "https://graph.qq.com/oauth2.0/me";
                //获得 openid
                string result = qq.SendCommand(opendIdUrl, new RequestParameter("access_token", qq.AccessToken));
                result = result.Substring(result.IndexOf("{"));
                result = result.Substring(0, result.LastIndexOf("}") + 1);
                var json = DynamicJson.Parse(result);
                if (!json.IsDefined("openid"))
                {
                    return View("Error", (object)"无法获得用户ID");
                }
                qq.OpenID = json.openid;
                if (qq.ClientID != json.client_id)
                    return RedirectToAction("Index", "Auth");

                //获得 用户信息 绑定
                var m = BaseModel.M<UserThirdPartyModel>();
                int uid = m.getUserId(qq.OpenID, 0);
                if (uid == 0)
                {
                    //获得 用户信息
                    string url = "https://graph.qq.com/user/get_user_info";
                    result = qq.SendCommand(url, new RequestParameter("access_token", qq.AccessToken),
                        new RequestParameter("oauth_consumer_key", qq.ClientID),
                        new RequestParameter("openid",qq.OpenID));
                    json = DynamicJson.Parse(result);
                    if (json.ret == 0)
                    {
                        ViewBag.Title = "绑定QQ";
                        ViewBag.Nick = json.nickname;
                        ViewBag.figureurl_1 = json.figureurl_qq_1;
                        Session[SEESION_CLIENT] = qq;
                        return View();//绑定手机号
                    }
                    else
                    {
                        return View("Error", (object)"无法获得用户QQ信息");
                    }
                }

               var r = this.Login(uid, "QQ登录");
               return Content(string.Format("<script language=\"javascript\">location.href='{0}';</script>", GetRedirectUrl(r.Token)));
            }

            return RedirectToAction("Index", "Auth");
        }

        /// <summary>
        /// 第三方登录微博
        /// </summary>
        /// <returns></returns>
        public ActionResult Weibo()
        {
            var sina = new SinaClient(WEIBOAPPID, "88068b05890e64d021db458717eae89c"
                , "http://pass.buildnet.cn/third/weibo");
            if (!string.IsNullOrWhiteSpace(Request["create"]))
            {
                string redirect = Request["redirect"];
                if (!string.IsNullOrWhiteSpace(redirect))
                    redirect = "&" + redirect;
                return Redirect(sina.GetAuthorizeUrl() + redirect);
            }
            if (!string.IsNullOrWhiteSpace(Request["code"]))
            {
                sina.GetAccessTokenByAuthorizationCode(Request["code"]);
                string opendIdUrl = "https://api.weibo.com/2/account/get_uid.json";
                //获得 openid
                string result = sina.SendCommand(opendIdUrl, new RequestParameter("access_token", sina.AccessToken));
                
                var json = DynamicJson.Parse(result);

                if (!json.IsDefined("uid"))
                {
                    return View("Error", (object)"无法获得用户ID");
                }

                sina.Uid = Convert.ToString(json.uid);
               
                //获得 用户信息 绑定
                var m = BaseModel.M<UserThirdPartyModel>();
                int uid = m.getUserId(sina.Uid, 2);
                if (uid == 0)
                {
                    //获得 用户信息
                    string url = "https://api.weibo.com/2/users/show.json";
                    result = sina.SendCommand(url, new RequestParameter("access_token", sina.AccessToken),
                        new RequestParameter("uid", sina.Uid));
                    json = DynamicJson.Parse(result);

                    if (json.IsDefined("error_code"))
                    {
                        return View("Error", (object)"获取用户微博信息时发生错误");
                    }
                    ViewBag.Nick = json.screen_name;
                    ViewBag.figureurl_1 = json.profile_image_url;
                    ViewBag.Title = "绑定微博";
                    Session[SEESION_CLIENT] = sina;
                    return View("QQ");//绑定手机号
                }

                var r = this.Login(uid, "微博登录");
                return Content(string.Format("<script language=\"javascript\">location.href='{0}';</script>", GetRedirectUrl(r.Token)));
            }

            return RedirectToAction("Index", "Auth");
        }

        public ActionResult Bind(FormCollection from)
        {
            #region 相关验证

            string phone = from["phone"] ?? "";
            if (string.IsNullOrWhiteSpace(phone))
            {
                return Json(new { msg = "手机号不能为空!", s = 1 });
            }

            string codeValue = from["codeValue"] ?? "";
            if (!ValidCode.IsValid(phone, codeValue))
            {
                return Json(new { s = 1, msg = "验证码不正确!" });
            }

            var blank = BaseModel.M<UserBlankListModel>().CheckIsIn(phone, 1);
            if (blank.Value)
            {
                return Json(new { s = 1, msg = "该手机号码不可用！" });
            }


            if (Session[SEESION_CLIENT] == null)
                return Json(new { msg = "错误的状态，请重新绑定！", s = 1, d = 0 });
            OpenPlatformClient client = (OpenPlatformClient)Session[SEESION_CLIENT];
            string tag = "";
            int type = 0;
            string loginInfo = "";
            if (client is TencentClient)
            {
                tag = (client as TencentClient).OpenID;
                type = 0;
                loginInfo = "QQ登录";
            }
            else if(client is SinaClient)
            {
                tag = (client as SinaClient).Uid;
                type = 2;
                loginInfo = "微博登录";
            }

            var m = BaseModel.M<UserThirdPartyModel>();
            int uid = m.getUserId(tag, type);
            if (uid != 0)//如果绑定过
            {
                return Json(new { msg = "错误的状态，请重新绑定！", s = 1, d = 0 });
            }
            
            var user = BaseModel.M<UserModel>();


            var dataUserName = user.getUserNameByValue(new { UserMobile = phone });//通过用户名称获取用户ID
            if (dataUserName != null)//手机号是否已经存在
            {
                return Json(new { msg = "手机号已经被注册，请重新填写！", s = 1, d = 0 });
            }

            #endregion

            dynamic ruser = null;
            uid = user.registerUser(phone, Guid.NewGuid().ToString("N").Substring(1,10)
                , phone, Request["services"]??"gcdx", "", "", "", out ruser);
            if (uid > 0)
            {
                m.Bind(tag, type, uid);
            }
            user.saveEq(new { NickName = Request["nick"], UserPhoto1 = Request["imgurl"] }, new { Id = uid });
            var r = this.Login(uid, loginInfo);

            return Json(new { msg = "绑定成功！", s = 0,url = GetRedirectUrl(r.Token)});
        }

        string GetRedirectUrl(string token)
        {
            string redirect = PageUrlConfig.BuildNetSite + "/membercenter";
            redirect = System.Text.RegularExpressions.Regex.Replace(redirect, @"&?token=([^&]*)", "");//去除源字符串中带有的无效Token
            if (redirect.IndexOf("?") != -1)
            {
                redirect = string.Format("{0}&token={1}", redirect, token);
            }
            else
            {
                redirect = string.Format("{0}?token={1}", redirect, token);
            }
            return redirect;
        }

        /// <summary>
        /// 配置登录
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="msg">日志说明</param>
        UserAccountToken Login(int uid, string msg)
        {
            //登录日志
            BaseModel.M<UserLoginLogModel>().AddLoginLog(uid, "", "", msg, Request);

            var user = BaseModel.M<UserModel>().getOneEq(new { Id = uid });

            var m = BaseModel.M<UserAccountTokenModel>();
            var r = m.Login(user.UserName, user.UserPass, 5, true);
            HttpCookie hc = new HttpCookie(AuthController.CookieKey);
            hc.Value = Security.EncryptString(string.Format("{0}|{1}", r.Value.Token, Tools.ConvertDateTimeInt(DateTime.Now)), AuthController.CookiePrivateKey);
            Response.Cookies.Add(hc);
            return r.Value;
        }


        protected override void OnException(ExceptionContext filterContext)
        {
            Ocor.Logger.LogWriter.Write(filterContext.Exception, filterContext.HttpContext.Request.RawUrl);
            filterContext.Result = RedirectToAction("Index", "Auth");
            base.OnException(filterContext);
        }
    }
}
